import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Table, Spin, Form, Row, Col, Input, Button, Dropdown, Menu, Icon, message, Modal, Select, Tree, TreeSelect, DatePicker, Checkbox, Tabs, InputNumber } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, getYear, getPayCycleDom, download } from 'lib/fun'
import AreaInput from 'components/areaInput'
import FilterModule from './filterCitizen'
import FilterModuleOrg from './filterCitizenOrg'

const TreeNode = Tree.TreeNode;
const Option = Select.Option;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;

const findRowDataProject = function(data, id){
  var find = false;
  _.each(data, (item)=>{
    var f = _.find(item.children, (i)=>{
      return i.projectId == id
    })
    if(f){
      find = f
    }
  });
  return find
}

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      projectCate: [],
      selectedKeys: [],      //选中项目keys
      selectedRowKeys: [],    //选中人员keys
      data: []
    }
    this.current = 1;   //当前第几页
    this.total = 0;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};
  }

  componentDidMount(){
    const { config, addConfig } = this.props;
    if(!config.genderCode){
      // 性别
      addConfig('genderCode', 7);
    }
    if(!config.nationCode){
      // 民族
      addConfig('nationCode', 5);
    }
    this.loadData();
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
      this.setState({
        selectedKeys: []
      });
    }
    if(nextProps.visible&&this.state.projectCate.length <= 0){
      if(nextProps.roleType){
        this.loadOrgProject();
      }else{
        this.loadProjectCate();
      }
    }
  }

  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadData = () => {
    var self = this;
    const { areaId, identNumber, name, master } = this.search;
    if(areaId){
      self.setState({
        loading: true
      });
      Ajax({
        url: '/citizen/list',
        data: {
          areaId,
          identNumber,
          name,
          master,
          currentPage: self.current,  //请求页码
          perPage: self.pageSize,   //每页数量
        },
        success: function(data){
          self.total = data.totalCount;
          self.setState({
            loading: false,
            data: data.list
          });
        },
        error: function(error){
          self.setState({
            loading: false
          });
          message.error(error);
        }
      });
    }
  }

  handleFilter = (option, all)=>{
    if(!_.isEqual(option, this.search)){
      this.search = option;
      if(this.search.areaId){
        this.loadData();
      }else{
        this.setState({
          data: []
        });
      }
    }
    if(all){
      this.handleCommit(true);
    }
  }

  areaChange = (option)=>{
    if(option.areaId){
      if(option.areaId != this.search.areaId){
        this.search = option;
        this.loadData();
      }
    }else{
      this.search = option;
      this.setState({
        data: []
      });
    }
  }

  loadProjectCate = ()=>{
    var self = this;
    Ajax({
      url: '/projectCate/list',
      success: function(data){
        var projectCate = []
        const loop = (data) => {
          data.forEach((item) => {
            const { projectCategoryId, projectCategoryCode, projectCategoryName } = item;
            projectCate.push({
              projectCategoryId, 
              projectCategoryCode, 
              projectCategoryName
            });
            if(item.children&&item.children.length > 0){
              loop(item.children);
            }
          });
        };
        loop(data);
        console.log(projectCate);
        self.setState({
          projectCate
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  onSelect = (info, e) => {
    if(e.selected){
      // var selected = findRowData(this.state.projectCate, info);
      // console.log(info, selected,e);
      if(info&&info.length>0&&/cate/.test(info[0])){
        // this.props.handleSelect(selected);
        this.setState({
          selectedKeys: []
        })
      }else{
        this.setState({
          selectedKeys: info
        })
      }
    }else{
      // this.props.handleSelect({});
    }
  }

  onLoadData = (treeNode)=>{
    var self = this;
    var selected = findRowData(self.state.projectCate, treeNode?treeNode.props.eventKey.replace('cate', ''):0);
    return new Promise((resolve) => {
      if(selected&&selected.children||this.props.roleType){
        resolve();
      }else{
        Ajax({
          url: '/project/list',
          data: {
            projectCategoryId: treeNode?treeNode.props.eventKey.replace('cate', ''):0,
            perPage: 10000
          },
          success: function(data){
            var projectCate = self.state.projectCate;
            if(projectCate&&projectCate.length > 0){
              projectCate = getNewTreeData(projectCate, treeNode.props.eventKey.replace('cate', ''), data.list);
            }
            self.setState({
              projectCate: projectCate
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  loadOrgProject = ()=>{
    var self = this;
    Ajax({
      url: '/project/listForOrg',
      data: {},
      success: function(data){
        self.setState({
          projectCate: [{
            projectCategoryId: 1234567,
            projectCategoryName: '全部',
            children: data
          }]
        });
        resolve();
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  handleCommit = (all) => {
    var self = this;
    const { type, rowdata, onShowBar } = this.props;
    self.props.form.validateFields((err, values) => {
      if(this.state.selectedKeys.length <= 0&&type != 3){
        message.error('请选择项目');
        return
      }
      if(!all&&this.state.selectedRowKeys.length <= 0){
        message.error('没有选择人员');
        return
      }
      if(err == null||type == 3){
        self.setState({
          loading: true
        });
        // onShowBar
        const { areaId, identNumber, name, master, batchId } = this.search;
        Ajax({
          url: type == 1?'/projectRegister/downTemplate':'/projectRegister/createRegisterBatch',
          data: {
            "projectId": type == 3?rowdata.projectId:this.state.selectedKeys[0],  //项目id
            "year": type == 3?rowdata.year:parseInt(values.year),  //年度
            "subsidyCount": type == 3?rowdata.subsidyCount:parseInt(values.subsidyCount),   //补贴次数
            areaId: parseInt(areaId),  //区划编号
            name,
            identNumber,
            master,   //是否户主
            "all": all?true:false, //是否导出全部
            "citizenInfoId": this.state.selectedRowKeys,
            batchId: type == 3?rowdata.batchId:undefined
          },
          success: function(data){
            self.setState({
              loading: false,
              selectedRowKeys: []
            });
            self.props.onClose();
            if(type == 1){
              download(data);
              message.success('导出成功');
            }else{
              onShowBar({
                barId: data.barId,
                typeId: data.typeId,
              });
            }
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onClose();
  }

  renderProject = ()=>{
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 9 },
      wrapperCol: { span: 10 },
    };
    const { visible, type, rowdata, roleType } = this.props;
    const citizenProperty = this.state.citizenProperty||{};
    const { genderCode, nationCode, degreeCode, relationCode, identTypeCode, citizenInfoTypeCode, householdTypeCode, fiveTypeCode } = this.props.config;
    
    const backTreeNode = item => {
      return <TreeNode title={item.projectName} key={item.projectId+""} value={item.projectId + ""} isLeaf={true}/>
    }

    const loop = data => data.map((item) => {
      if (item.projectCategoryId&&!item.projectId) {
        return (<TreeNode title={item.projectCategoryName} key={"cate" + item.projectCategoryId+""} value={"cate" + item.projectCategoryId}>{
          (item.children||[]).map((i)=>{
            return backTreeNode(i)
          })
        }</TreeNode>);
      }else{
        return backTreeNode(item)
      }
    });
    const treeNodes = loop(this.state.projectCate);
    const years = getYear();
    const subsidyCount = function(){
      if(this.state.selectedKeys.length > 0){
        var selected = findRowDataProject(this.state.projectCate, this.state.selectedKeys[0]);
        console.log(selected);
        if(selected){
          return getPayCycleDom(selected.payCycleCode);
        }else{
          return null
        }
      }else{
        return null
      }
    }.bind(this);
    return type == 3?(
        <div className="batch-append">
          <FormItem {...formItemLayout} label="项目名称">
            {rowdata.projectName}
          </FormItem>
          <FormItem {...formItemLayout} label="发放年度">
            {rowdata.year}
          </FormItem>
          <FormItem {...formItemLayout} label="补贴次数">
            {rowdata.subsidyCount}
          </FormItem>
        </div>
      ):(
      <div>
        <Tree
          autoExpandParent
          selectedKeys={this.state.selectedKeys}
          onSelect={this.onSelect} 
          loadData={this.onLoadData}
        >
          { treeNodes }
        </Tree>
        <FormItem {...formItemLayout} label="发放年度">
          {getFieldDecorator("year",{
            rules: [{
              required: true, message: '请选择发放年度',
            }]
          })(
            <Select disabled={this.state.selectedKeys.length<=0} size="default">
              {
                years.map(function(y){
                  return (<Option key={y+""} value={ y+"" }>{ y+"" }</Option>)
                })
              }
            </Select>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label="补贴次数">
          {getFieldDecorator("subsidyCount",{
            rules: [{
              required: true, message: '请选择补贴次数',
            }]
          })(
            <Select disabled={this.state.selectedKeys.length<=0} size="default">
              { subsidyCount() }
            </Select>
          )}
        </FormItem>
      </div>
    )
  }

  renderPeople = ()=>{
    var self = this;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 18 },
      wrapperCol: { span: 6 },
    };
    const { visible, type, roleType } = this.props;
    const { bankCode } = this.props.config;

    const { config } = this.props;
    const columns = [{
      title: '用户姓名',
      dataIndex: 'name'
    }, {
      title: '证件号码',
      dataIndex: 'identNumber'
    }, {
      title: '性别',
      dataIndex: 'genderCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'genderCode', text) }</span>)
    }, {
      title: '出生年月',
      dataIndex: 'birthday'
    }, {
      title: '民族',
      dataIndex: 'nationCode',
      render: (text, record) => (<span>{ getNameByCode(config, 'nationCode', text) }</span>)
    }, {
      title: '是否户主',
      dataIndex: 'master',
      render: (text, record) => (<span>{ text?"是":"否" }</span>)
    }, {
      title: '户口簿编号',
      dataIndex: 'householdRegisterNumber'
    }, {
      title: '补贴登记区划',
      dataIndex: 'areaName'
    }];

    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange,
      showTotal: total => `总共 ${total} 条`
    };

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        self.setState({
          selectedRowKeys: selectedRowKeys
        });
      },
      selectedRowKeys: this.state.selectedRowKeys
    };

    return (
      <div>
        {
        roleType?<FilterModuleOrg 
          handleFilter={ this.handleFilter }
          areaChange={ this.areaChange }
          num={this.total}
          type={type}
        />:<FilterModule 
          handleFilter={ this.handleFilter }
          areaChange={ this.areaChange }
          treeData={this.props.treeData}
          num={this.total}
          type={type}
        />
        }
        <Table 
          columns={columns}
          dataSource={ this.state.data }
          rowKey="citizenInfoId"
          size="small"
          locale={{
            emptyText: this.search.areaId?<span><Icon type="frown-o" />此区划下无用户数据</span>:<span><Icon type="info-circle-o" />请先选择区划</span>
          }}
          pagination={ pagination }
          rowSelection={ rowSelection }
        />
      </div>
    )
  }

  getTitle = ()=>{
    const { type } = this.props;
    var back = '新建登记补报填报表';
    switch(type){
      case 2: back = "新建补贴登记项目";break;
      case 3: back = "新增补贴人员";break;
      default: break;
    }
    return back
  }

  getOkText = ()=>{
    const { type } = this.props;
    var back = '导出模板'
    if(type == 1){
      back = "导出模板"+(this.state.selectedRowKeys.length>0?this.state.selectedRowKeys.length+"人":"")
    }else if(type == 2){
      back = "选中"+(this.state.selectedRowKeys.length>0?this.state.selectedRowKeys.length:0) + "人"
    }else if(type == 3){
      back = "新增"+(this.state.selectedRowKeys.length>0?this.state.selectedRowKeys.length:0) + "人"
    }
    return back
  }

  render() {
    const { visible, type } = this.props;
    
    return (
            <Modal 
              title={this.getTitle()}
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText={this.getOkText()} 
              cancelText="取消"
              width="1100px"
              wrapClassName="create-submit"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <Row>
                    <Col span={5}>
                      { this.renderProject() }
                    </Col>
                    <Col span={19} >
                      <div className="right-people">
                        { this.renderPeople() }
                      </div>
                    </Col>
                  </Row>
                </Form>
              </Spin>
            </Modal>
            );
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(Form.create()(ModuleName))

